
import UIKit

public enum LanguageType: String {
    case zh = "zh-Hans"
    case en = "en"
}

public class LanguageManager {
    
    public static let shared = LanguageManager()
    
    private static let userDefaultsKey = "current_language"
    private static let defautLanguage = LanguageType.zh
    
    init() {
        currentLanguage = LanguageType(rawValue: LanguageManager.storedCurrentLanguage ?? LanguageManager.defautLanguage.rawValue) ?? LanguageManager.defautLanguage
    }
    
    /// 可用的语言
    public static var availableLanguages: [String] {
        Bundle.main.localizations.sorted()
    }
    
    /// 当前语言
    public var currentLanguage: LanguageType {
        didSet {
            storeCurrentLanguage()
        }
    }
    
    /// 当前语言展示的名字
    public var currentLanguageDisplayName: String? {
        displayName(language: currentLanguage.rawValue)
    }
    
    /// 根据语言国际化展示的名字
    public func displayName(language: String) -> String? {
        (currentLocale as NSLocale).displayName(forKey: NSLocale.Key.identifier, value: language)?.capitalized
    }
    /// 原始语言显示名称
    public static func nativeDisplayName(language: String) -> String? {
        let locale = NSLocale(localeIdentifier: language)
        return locale.displayName(forKey: NSLocale.Key.identifier, value: language)?.capitalized
    }
    
    /// 更换语言弹框
    public func exchangeLanguage() {
        
        AppActionSheet(titles: [AppActionSheetItem(title: "简体中文".localized), AppActionSheetItem(title: "英文".localized)]) { title, index in
            
            var nowLanguage = LanguageType.zh
            if title == "简体中文".localized {
                nowLanguage = .zh
            } else if title == "英文".localized {
                nowLanguage = .en
            }
            
            guard nowLanguage != LanguageManager.shared.currentLanguage else { return }
            LanguageManager.shared.currentLanguage = nowLanguage
            
            DispatchQueue.main.asyncAfter(deadline: .now()+0.5) {
                NotificationCenter.default.post(name: NSNotification.Name("TabbarReloadItemNotification"), object: nil)
            }
            
            DispatchQueue.main.async {
                _ = UIViewController.getAllViewControllers().map { vc in
                    if let subVC = vc as? BaseViewController {
                        subVC.refreshData()
                    }
                }
            }
            //            NotificationCenter.default.post(name: NSNotification.Name("ResetRootVC"), object: nil)
            
        }.show()
        
    }
    
}

extension LanguageManager {
    
    /// 存储当前语言
    private func storeCurrentLanguage() {
        UserDefaults.standard.set(currentLanguage.rawValue, forKey: LanguageManager.userDefaultsKey)
    }
    
    /// 获取存设置的语言
    private static var storedCurrentLanguage: String? {
        UserDefaults.standard.value(forKey: userDefaultsKey) as? String
    }
    
    /// 推荐语言
    private static var preferredLanguage: String? {
        Bundle.main.preferredLocalizations.first { availableLanguages.contains($0) }
    }
}

extension LanguageManager {
    
    public var currentLocale: Locale {
        Locale(identifier: currentLanguage.rawValue)
    }
}

extension LanguageManager {
    
    public func localize(string: String, bundle: Bundle?) -> String {
        if let languageBundleUrl = bundle?.url(forResource: currentLanguage.rawValue, withExtension: "lproj"), let languageBundle = Bundle(url: languageBundleUrl) {
            return languageBundle.localizedString(forKey: string, value: nil, table: "Localizable")
        }
        
        return string
    }
    
    public func localize(string: String, bundle: Bundle?, arguments: [CVarArg]) -> String {
        String(format: localize(string: string, bundle: bundle), locale: currentLocale, arguments: arguments)
    }
}
